package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.Order;
import com.jt.service.DubboCartService;
import com.jt.service.DubboOrderService;
import com.jt.util.UserThreadLocal;
import com.jt.vo.SysResult;
import org.jboss.netty.util.internal.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author 张琪
 * @date 2020/12/17
 * @describe
 */
@Controller
@RequestMapping("/order")
public class OrderController {


    @Reference(check = false)
    private DubboCartService cartService;

    @Reference(check = false)
    private DubboOrderService orderService;

    @RequestMapping("/create")
    public String orderCart(Model model) {
        long userId = UserThreadLocal.getUser().getId();
        List<Cart> cartList = cartService.findAllCartById(userId);
        model.addAttribute("carts", cartList);
        return "order-cart";
    }

    /**
     * 业务需求: 实现订单入库操作
     * url: http://www.jt.com/order/submit
     *
     * @param order
     * @return SysResult对象(orderId)
     */

    @RequestMapping("/submit")
    @ResponseBody
    public SysResult doSubmit(Order order) {
        Long userId = UserThreadLocal.getUser().getId();
        order.setUserId(userId);
        String orderId = orderService.saveOrder(order);
        if (StringUtils.hasLength(orderId)) {
            return SysResult.success(orderId);
        }
        return SysResult.fault();
    }


    @RequestMapping("/success")
    public String success(@RequestParam("id") String orderId, Model model) {
        Order order = orderService.findOrderById(orderId);
        model.addAttribute("order", order);
        return "success";
    }
}
